const express = require('express')
const cors = require('cors')

const app = express()

// 配置cors中间件
app.use(cors())

// 配置解析表单数据的中间件
app.use(express.urlencoded({extended: false}))

// 引入解析token的中间件
const expressJwt = require('express-jwt')
const screctKey = require('./config')
app.use(expressJwt({secret: screctKey.screctKey}).unless({path: [/^\/zlx\//]}))

// 封装抛出错误的中间件
app.use((req, res, next) => {
    // console.log(req.body, 'hahaha');
    res.err = (err, state=400) => {
        res.send({state, message: err instanceof Error ? err.message : err})
    }
    next()
})

const router = require('./router/user')
const userinfoRouter = require('./router/userinfo')
const Joi = require('joi')

app.use('/zlx', router)
app.use('/my', userinfoRouter)

// 定义错误级别中间件
app.use((err, req, res, next) => {
    // console.log(req.body);
    if (err instanceof Joi.ValidationError) {
        return res.err(err)
    }
    console.log(err.name === 'UnauthorizedError', 'hahaha');
    if (err.name === 'UnauthorizedError') {
        return res.err('身份认证失败')
    }
    res.err(err)
})

app.listen(8080, () => {
    console.log('express server is running at http://127.0.0.1:8080');
})